<template>
  <div class="page-fina-details">
    <div class="search-bar">
      <el-form
        :inline="true"
        class="search-form"
        @submit.prevent
      >
        <div class="input-row">
          <!-- 订单编号 -->
          <el-form-item :label="$t('order.number') + ':'">
            <el-input
              v-model="orderId"
              style="min-width: 220px;"
              clearable
              :placeholder="$t('finaManage.pleEntOrderNum')"
            />
          </el-form-item>
          <!--支付方式 -->
          <el-form-item :label="$t('order.paymentMethod') + ':'">
            <el-select
              v-model="paymentMethodValue"
              clearable
              @change="setPaymentMethodRange(paymentMethodValue)"
            >
              <el-option
                v-for="item in paymentMethodOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- 交易时间 -->
          <el-form-item
            :label="$t('finaManage.transactionHour') + ':'"
            class="date-range-param"
          >
            <el-select
              v-model="datePickerType"
              class="date-picker-type"
              @change="setdatePickerType(datePickerType)"
            >
              <el-option
                v-for="item in datePickerTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-date-picker
              v-model="dateRangeParam"
              :type="datePickerType"
              clearable
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :range-separator="$t('date.tip')"
              :start-placeholder="$t('date.start')"
              :end-placeholder="$t('date.end')"
            />
          </el-form-item>
          <!-- 按钮 -->
          <el-form-item>
            <div
              class="primary-btn default-btn"
              @click="queryData"
            >
              {{ $t('order.query') }}
            </div>
            <div
              class="default-btn"
              @click="resetData"
            >
              {{ $t('product.reset') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div class="main-container">
      <div class="operation-bar">
        <div
          v-if="isAuth('finance:detail:excel')"
          class="default-btn primary-btn"
        >
          <a @click="exportFrom()">{{ $t('order.exportForm') }}</a>
        </div>
      </div>
      <div class="table-con">
        <el-table
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          :data="tableData"
          style="width: 99%"
        >
          <!-- :render-header="renderHeadeTime" -->
          <el-table-column
            prop="transDate"
            width="160"
            :label="$t('finaManage.transactionHour')"
          />
          <!-- :render-header="renderHeadeThree" -->
          <el-table-column
            prop="orderNumber"
            width="170"
            :label="$t('order.number')"
          />
          <el-table-column
            prop="placeTime"
            width="160"
            :label="$t('order.createTime')"
          />
          <el-table-column
            prop="prodName"
            :label="$t('order.transactionSummary')"
          />
          <el-table-column
            prop="shopName"
            :label="$t('order.occurrenceChannel')"
          />
          <el-table-column
            prop="userName"
            :label="$t('order.fundingChangeApplicant')"
          >
            <template #default="scope">
              {{ scope.row.userName || $t('order.userLoggedOut') }}
            </template>
          </el-table-column>
          <el-table-column
            prop="bizPayNo"
            :label="$t('order.payPlatformTransactionTicketNumber')"
          >
            <template #default="scope">
              {{ scope.row.bizPayNo ? scope.row.bizPayNo : '-' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="bizType"
            :label="$t('order.businessType')"
          >
            <template #default="scope">
              <span>
                {{
                  [
                    '',
                    $t("order.orderPaymentS"),
                    $t("order.orderRefunds"),
                    $t("order.balanceTopUp"),
                    $t("order.purchaseMembership")
                  ][scope.row.bizType]
                }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="payType"
            :label="$t('order.paymentMethod')"
          />
          <el-table-column
            prop="transAmount"
            :label="$t('order.amountIncomeAndExpenditure')"
          />
        </el-table>
      </div>
      <el-pagination
        class="paging"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageTotal"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ElMessage, ElLoading } from 'element-plus'
import { onMounted, reactive } from 'vue'
import moment from 'moment'
import { isAuth } from '@/utils'

const Data = reactive({
  orderId: '', // 单号输入
  dateRangeParam: [moment().add(-7, 'days').startOf('day').format('YYYY-MM-DD'), moment().add(-1, 'days').endOf('day').format('YYYY-MM-DD')],
  startTime: '',
  endTime: '',
  paymentMethodValue: null,
  datePickerTypeOptions: [
    {
      label: $t('date.daterange'),
      value: 'daterange'
    },
    {
      label: $t('date.monthrange'),
      value: 'monthrange'
    }
  ],
  datePickerType: 'daterange', // 日期筛选类型

  incPayType: 0, //  筛选条件
  payType: -1, // 当前选中的支付方式 -1表示不限
  payTypeList: [$t('order.pointsPayment'), $t('order.wecProPay'), $t('platform.aliPay'), $t('order.wechatScanCodePayment'), $t('order.wechatH5Payment'), $t('order.weclAccountPay'), $t('order.alipayH5Payment'), $t('order.alipayAPPPayment'), $t('order.wechatAPPPayment'), $t('order.balancePayment'), $t('order.payPalPayment')], // 所有支付方式

  tableData: [], //  表格数据

  currentPage: 1, // 当前页数
  pageSize: 10, // 每页显示多少条
  pageTotal: 0, // 一共多少条数据

  tempFormData: null
})

const allinpayStore = useAllinpayStore()
const paySettlementType = computed(() => {
  return allinpayStore.paySettlementType
})

const paymentMethodOptions = computed(() => {
  const optionsVal = [
    {
      label: $t('order.pointsPayment'),
      value: 0
    },
    {
      label: $t('order.wecProPay'),
      value: 1
    },
    {
      label: $t('platform.aliPay'),
      value: 2
    },
    {
      label: $t('order.wechatScanCodePayment'),
      value: 3
    },
    {
      label: $t('order.wechatH5Payment'),
      value: 4
    },
    {
      label: $t('order.weclAccountPay'),
      value: 5
    },
    {
      label: $t('order.alipayH5Payment'),
      value: 6
    },
    {
      label: $t('order.alipayAPPPayment'),
      value: 7
    },
    {
      label: $t('order.wechatAPPPayment'),
      value: 8
    },
    {
      label: $t('order.balancePayment'),
      value: 9
    },
    {
      label: $t('order.payPalPayment'),
      value: 10
    }
  ]

  if (paySettlementType.value === 1) {
    return optionsVal.filter((item) => {
      return item.value !== 10
    })
  }
  return optionsVal
})

const { orderId, dateRangeParam, paymentMethodValue, datePickerTypeOptions, datePickerType, tableData, currentPage, pageSize, pageTotal } = toRefs(Data)

onMounted(() => {
  getFinaDetailsData()
})

const queryData = () => {
  Data.currentPage = 1
  getFinaDetailsData()
}

// 点击查询
const getFinaDetailsData = () => {
  Data.tempFormData = Object.assign({
    startTime: Data.dateRangeParam ? Data.dateRangeParam[0] + ' 00:00:00' : '',
    endTime: Data.dateRangeParam ? Data.dateRangeParam[1] + ' 23:59:59' : '',
    orderNumber: Data.orderId,
    payType: Data.payType,
    current: Data.currentPage,
    size: Data.pageSize
  })
  http({
    url: http.adornUrl('/platform/financialManagement/getFinanceDetail'),
    method: 'get',
    params: http.adornParams({
      ...Data.tempFormData
    })
  }).then(({ data }) => {
    Data.tableData = data.records
    // 将支付类型（int）转中文（str）
    Data.tableData.forEach(element => {
      element.payType = Data.payTypeList[element.payType]
      if (element.incPayType === '1') {
        element.incPayType = $t('shop.income')
      } else {
        element.incPayType = $t('shop.pay')
      }
    })
    Data.currentPage = data.current
    Data.pageSize = data.size
    Data.pageTotal = data.total
  })
}

// 清空
const resetData = () => {
  Data.orderId = null
  Data.payType = -1
  Data.incPayType = 0
  Data.paymentMethodValue = null
  Data.dateRangeParam = null
}

const exportFrom = () => {
  if (!Data.dateRangeParam) {
    ElMessage.warning($t('tip.select') + $t('finaManage.transactionHour'))
    return
  }
  const loading = ElLoading.service({
    lock: true,
    target: '.main-container',
    customClass: 'export-load',
    background: 'transparent',
    text: $t('shop.exportIng')
  })
  http({
    url: http.adornUrl('/platform/financialManagement/getFinanceDetailForm'),
    method: 'get',
    params: http.adornParams({
      ...Data.tempFormData
    }),
    responseType: 'blob'
  }).then(({ data }) => {
    loading.close()
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    let fileName = $t('finaManage.finaDeta')
    if (Data.dateRangeParam[0] !== Data.dateRangeParam[1]) {
      fileName = fileName + '(' + Data.dateRangeParam[0] +
        ' ' + $t('date.tip') + ' ' +
        Data.dateRangeParam[1] + ')'
    } else {
      fileName = fileName + `(${Data.dateRangeParam[0]})`
    }
    fileName = fileName + '.xlsx'

    const elink = document.createElement('a')
    if ('download' in elink) { // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  }).catch((e) => {
    loading.close()
  })
}

// 0：积分支付  1：微信小程序支付  2：支付宝 3：微信扫码支付  4：微信H5支付  5：微信公众号支付 6：支付宝H5支付  7：支付宝APP支付  8：微信App支付  9：用户余额支付  10：PayPal支付
const setPaymentMethodRange = (val) => {
  Data.payType = (val === 0 || val) ? val : -1
}

const setdatePickerType = (val) => {
  Data.currentPage = 1
  Data.datePickerType = val
}

// 页数的切换
const handleSizeChange = (val) => {
  Data.pageSize = val
  Data.tempFormData.size = val
  getFinaDetailsData()
}

//  换页
const handleCurrentChange = (val) => {
  Data.currentPage = val
  Data.tempFormData.current = val
  getFinaDetailsData()
}

</script>

<style lang="scss" scoped>
.page-fina-details {

  .default-btn {
    a {
      text-decoration: none;
      color: unset;
    }
  }
}

.date-picker-type {
  width: 120px !important;
}

:deep(.date-picker-type .el-input--suffix) {
  width: 120px !important;
}

:deep(.el-range-separator) {
  width: 18px;
}

:deep(.el-date-editor--daterange) {
  width: 300px !important;
}

:deep(.date-range-param .el-form-item__label:before) {
  color: #F56C6C;
  margin-right: 4px;
  content: '*';
}

:deep(.search-bar .input-row .el-form-item__content .el-input) {
  width: 100%;
}
</style>
